package com.test.demo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.test.demo.R;
import com.test.demo.model.Moment;

import java.util.ArrayList;
import java.util.List;

import client.PhotoClient;
import client.PhotoMoreResultBean;
import client.PhotoPreviewClient;
import client.PhotoSelectResultBean;
import client.activity.BGAPPToolbarActivity;
import client.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 你自己项目里「可以不继承 BGAPPToolbarActivity」，我在这里继承 BGAPPToolbarActivity 只是为了方便写 Demo
 */
public class MomentAddActivity extends BGAPPToolbarActivity implements EasyPermissions.PermissionCallbacks, BGASortableNinePhotoLayout.Delegate {
    private static final int PRC_PHOTO_PICKER = 1;

    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;

    private static final String EXTRA_MOMENT = "EXTRA_MOMENT";

    // ==================================== 测试图片选择器 START ====================================
    /**
     * 是否是单选「测试接口用的」
     */
    private CheckBox mSingleChoiceCb;
    /**
     * 是否具有拍照功能「测试接口用的」
     */
    private CheckBox mTakePhotoCb;
    // ==================================== 测试图片选择器 END ====================================

    // ==================================== 测试拖拽排序九宫格图片控件 START ====================================
    /**
     * 是否可编辑
     */
    private CheckBox mEditableCb;
    /**
     * 是否显示九图控件的加号按钮「测试接口用的」
     */
    private CheckBox mPlusCb;
    /**
     * 是否开启拖拽排序功能「测试接口用的」
     */
    private CheckBox mSortableCb;
    /**
     * 拖拽排序九宫格控件
     */
    private BGASortableNinePhotoLayout mPhotosSnpl;
    // ==================================== 测试拖拽排序九宫格图片控件 END ====================================

    private EditText mContentEt;

    public static Moment getMoment(Intent intent) {
        return intent.getParcelableExtra(EXTRA_MOMENT);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_moment_add);
        mSingleChoiceCb = findViewById(R.id.cb_moment_add_single_choice);
        mTakePhotoCb = findViewById(R.id.cb_moment_add_take_photo);

        mEditableCb = findViewById(R.id.cb_moment_add_editable);
        mPlusCb = findViewById(R.id.cb_moment_add_plus);
        mSortableCb = findViewById(R.id.cb_moment_add_sortable);

        mContentEt = findViewById(R.id.et_moment_add_content);
        mPhotosSnpl = findViewById(R.id.snpl_moment_add_photos);

        PhotoClient.getClient().selectPhotoResult(this, new PhotoClient.PhotoResult() {
            @Override
            public void back(PhotoSelectResultBean result) {
                Log.e("选择图片返回", result.getTag() + "       " + result.getResult().toString());
                if (mSingleChoiceCb.isChecked()) {
                    mPhotosSnpl.setData(result.getResult());
                } else {
                    mPhotosSnpl.addMoreData(result.getResult());
                }
            }
        });

        PhotoClient.getClient().takePhotoResult(this, new PhotoClient.PhotoResult() {
            @Override
            public void back(PhotoSelectResultBean result) {
                Log.e("拍照返回", result.getTag() + "       " + result.getResult().toString());
                PhotoClient.getClient().setPhotoResultTag(this.getClass().getName());
                mPhotosSnpl.addMoreData(result.getResult());
            }
        });

        PhotoClient.getClient().addMoreClickListener(result -> {
            Log.e("addMoreClickListener", result.getTag() + "       " + result.getPaths().toString());
            Log.e("addMoreClickListener", "第" + result.getPosition() + "位置");
        });

    }

    @Override
    protected void setListener() {
        mSingleChoiceCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked) {
                    mPhotosSnpl.setData(null);
                    mPhotosSnpl.setMaxItemCount(1);
                } else {
                    mPhotosSnpl.setMaxItemCount(9);
                }
            }
        });
        mEditableCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                mPhotosSnpl.setEditable(checked);
            }
        });
        mPlusCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                mPhotosSnpl.setPlusEnable(checked);
            }
        });
        mSortableCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                mPhotosSnpl.setSortable(checked);
            }
        });

        // 设置拖拽排序控件的代理
        mPhotosSnpl.setDelegate(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        setTitle("添加朋友圈");

        mEditableCb.setChecked(mPhotosSnpl.isEditable());
        mPlusCb.setChecked(mPhotosSnpl.isPlusEnable());
        mSortableCb.setChecked(mPhotosSnpl.isSortable());
    }

    public void onClick(View v) {
        if (v.getId() == R.id.tv_moment_add_choice_photo) {
            choicePhotoWrapper();
        } else if (v.getId() == R.id.tv_moment_add_publish) {
            String content = mContentEt.getText().toString().trim();
            if (content.length() == 0 && mPhotosSnpl.getItemCount() == 0) {
                Toast.makeText(this, "必须填写这一刻的想法或选择照片！", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent();
            intent.putExtra(EXTRA_MOMENT, new Moment(mContentEt.getText().toString().trim(), mPhotosSnpl.getData()));
            setResult(RESULT_OK, intent);
            finish();
        } else if (v.getId() == R.id.tv_moment_add_take_photo) {
            PhotoClient.getClient().setDefault().setPhotoResultTag(getClass().getName()).setFrontCamera(true).takePhoto(MomentAddActivity.this);
        } else if (v.getId() == R.id.tv_moment_add_take_photo_crop) {
            PhotoClient.getClient().setDefault().setPhotoResultTag(getClass().getName()).setCropPhoto(true).takePhoto(MomentAddActivity.this);
        }

    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotosSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        /*PhotoClient.getClient().setDefault()
                .setPhotoResultTag(this.getClass().getName())
                .setMultiSelectPhoto(mSingleChoiceCb.isChecked())
                .setmMultiSelectNum(mPhotosSnpl.getMaxItemCount())
                .setmCurrentPosition(position)
                .setShowMore(true)
                .setTakePhoto(mTakePhotoCb.isChecked())
                .setSelectPhotoList(models)
                .startPhotoPreview(MomentAddActivity.this);*/

        PhotoPreviewClient.getClient().setDefault()
                .setPhotoResultTag(this.getClass().getName())
                .setSelectPhotoList(models)
                .setmCurrentPosition(position)
                .setShowMore(true)
                .setShowTitle(true)
                .addMoreClickListener(new PhotoPreviewClient.MoreClickListener() {
                    @Override
                    public void click(PhotoMoreResultBean photoMoreResultBean) {
                        Log.e("PhotoMoreResultBean", photoMoreResultBean.getTag() + "--" + photoMoreResultBean.getPosition() + "--" + photoMoreResultBean.getPaths().toString());
                        PhotoPreviewClient.getClient().runSaveShowImage();
                    }
                })
                .addGetSaveShowImageListener(new PhotoPreviewClient.GetSaveShowImageListener() {
                    @Override
                    public void save(String path) {
                        Log.e("图片的保存的路径为", path);
                    }
                })
                .start(this);

        //startActivity(new Intent(MomentAddActivity.this, PhotoPickerPActivity.class));
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {
        Toast.makeText(this, "排序发生变化", Toast.LENGTH_SHORT).show();
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {

        PhotoClient.getClient().setDefault()
                .setPhotoResultTag(this.getClass().getName())
                .setmMultiSelectNum(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount())
                .setTakePhoto(mTakePhotoCb.isChecked())
                .setCropPhoto(false)
                .startPhotoPicker(MomentAddActivity.this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }


}